<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { SubjectApi } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { addCheckSubject, EnumApi, getSubjectList } from '#/api';
import { messageSuccess } from '#/utils';

import { useChildSearchForm, useChildSubjectColumns } from './modelData';

const emit = defineEmits(['success']);
// 存储选中行的响应式变量
const selectedRows = ref<SubjectApi.CheckRow[]>([]);
const formData = ref<SubjectApi.CheckRow>();
const title = ref<string>();
const showConfrimBtn = ref(true);

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看设备';
  return formData.value?.attr1 === '2' ? '修改设备' : '添加设备';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});
const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: true,
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<SubjectApi.CheckRow>();
      if (data) {
        // 修改为使用 dayjs 格式化日期字符串，避免类型不匹配问题
        if (data.createTime) {
          data.createTime = dayjs(data.createTime) as any as Date;
        }
        formData.value = data;
        // formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
  async onConfirm() {
    if (selectedRows.value.length > 0) {
      for (let i = 0; i < selectedRows.value.length; i++) {
        const selectedRow = selectedRows.value[i];
        selectedRow!.planId = formData.value?.planId!;
        await addCheckSubject(selectedRows.value[i]!);
        messageSuccess('操作成功');
      }
    }

    modalApi.close();
    emit('success');
  },
});

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-3 gap-x-5 gap-y-4',
  schema: useChildSearchForm(),

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

/**
 * 表格配置
 */
const gridOptions: VxeGridProps<SubjectApi.CheckRow> = {
  columns: useChildSubjectColumns(),
  checkboxConfig: {
    highlight: true,
  },

  scrollbarConfig: {
    x: {
      position: 'bottom',
    },
  },
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    slots: {
      // 自定义分页器
    },
    // 每页显示数量选择
    pageSizes: [5, 10, 20, 50, 100],
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getSubjectList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          subjectType: EnumApi.DvPlanTypeEnum.CHECK,
          ...formValues,
        });
        return { items: res.rows, total: res.total };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    // custom: true,
    // zoom: true,
    refresh: { code: 'query' },
  },
};

const gridEvents: VxeGridListeners = {
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 * 刷新表格
 */
// function refreshGrid() {
//   gridApi.query();
// }
</script>

<template>
  <Modal
    title="项目选择"
    class="w-[80%]"
    :show-confirm-button="false"
    :show-cancel-button="false"
  >
    <Grid class="ml-2" />
    <!-- <Form class="mx-4" /> -->
    <template #prepend-footer>
      <div class="flex flex-auto justify-center">
        <div class="flex gap-2">
          <Button type="primary" @click="modalApi.onConfirm"> 确认 </Button>
          <Button @click="modalApi.onCancel"> 取消 </Button>
        </div>
      </div>
    </template>
  </Modal>
</template>
